/**
 * @author 雷明浩
 * @date 2025/5/29 10:56
 */
public class ReverseKGroup {
    // leetcode k个一组翻转链表
    // https://leetcode.cn/problems/reverse-nodes-in-k-group/?envType=study-plan-v2&envId=top-100-liked
    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || head.next == null) return head;
        ListNode cur = head;
        ListNode prev = null;
        for (int i = 0; i < k; i++) {
            prev = cur;
            cur = cur.next;
            if (cur == null && i != k-1) return head;
        }
        prev.next = null;
        ListNode nextList = reverseKGroup(cur, k);
        ListNode phead = revserseList(head);
        head.next = nextList;
        return phead;
    }

    private ListNode revserseList(ListNode head) {
        ListNode prev = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode nextCur = cur.next;
            cur.next = prev;
            prev = cur;
            cur = nextCur;
        }
        return prev;
    }
}